package service;

import com.alibaba.druid.pool.GetConnectionTimeoutException;
import entity.Book;
import entity.BorrowBook;
import entity.Reader;
import entity.ReaderType;
import function.*;
import interfaces.BorrowBookServiceDao;
import tool.MyTool;
import tool.TSUtility;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class BorrowBookServiceImpl implements BorrowBookServiceDao {

    BorrowBookDaoImpl borrowBookDao = new BorrowBookDaoImpl();
    ReaderDaoImpl readerDao = ReaderDaoImpl.getReaderDao();

    BorrowBookDaoImpl borrowBook = BorrowBookDaoImpl.getBorrowBook();
    BookServiceImpl bookService = new BookServiceImpl();
    BookBaseDao2Impl bookBaseDao2 =BookBaseDao2Impl.getBaseDao2();
    ReaderServiceDaoImpl readerServiceDao=new ReaderServiceDaoImpl();
    //
    @Override
    public void borrowBooks() {
        FineServiceImpl fineService1 = new FineServiceImpl();
        BorrowBook borrowBook = new BorrowBook();
        Connection connection = null;
        try {
            connection = Druid.getConnection();
            List<Reader> listReader = readerDao.getAll(connection);

            MyTool.printArr(listReader);
            System.out.println("输入你要选择的读者-(序号)");
            Integer typeIndex1 = MyTool.getTypeIndex(listReader.size());
            //输出读者ID
            String readerid = listReader.get(typeIndex1).getReaderid();
            if(readerid.equals(""))
                System.out.println();
            //1、判断读者是否有罚金类型
            boolean b = fineService1.judgmentExist(readerid);
            if (b == false) {
                System.out.println("该读者还无罚金类型，请先前往添加");
                return;
            }
            List<Book> listBook = bookBaseDao2.getAll(Druid.getConnection());
            MyTool.printArr(listBook);


            System.out.println("选择你要借的书—(序号)");
            Integer typeIndex = MyTool.getTypeIndex(listBook.size());
            //输出选择的ISBN
            String ISBN = listBook.get(typeIndex).getISBN();


            // 优化部分**********************************
            //1、借书数量是否上限

          // 该读者借了几本书
            int borrowMax = getBorrowMax(readerid);
            System.out.println("借了"+borrowMax);
            int reader_typeID = getReader_typeID(readerid);
           //该读者能借几本书
            int i = judgmentBorrowMax(reader_typeID);
            System.out.println("能借"+i);
            if(i==borrowMax){
                System.out.println("该读者只能借"+i+"本书"+"已经借了"+borrowMax+"，归还已借图书或提升用户等级");
                System.out.println("是否立即提升用户等级：（Y/N）?");
                char c = TSUtility.readConfirmSelection();
                if(c=='N'){
                    return;
                }
                readerServiceDao.upGrade(readerid);
                return;
            }

            BookBaseDao2Impl dao2 = BookBaseDao2Impl.getBaseDao2();
            Book bookByISBN = dao2.getBookByISBN(Druid.getConnection(), ISBN);
            if (bookByISBN.getNumber() <= 0) {
                System.out.println("该书已经被就借完，是否添加库存（Y/N）？");
                char c = TSUtility.readConfirmSelection();
                if(c=='N')
                return;
                bookService.addNumber(ISBN);
            }
            System.out.println("--------------------------------");
            System.out.println("温馨提示");
            System.out.println("该读者借书详情——可借：" + i + "本");
            System.out.println("该读者借书详情——已借:" + borrowMax + "本");
            System.out.println("注意借书数量哟");
            System.out.println("--------------------------");
            System.out.println();
            Date regdate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String s = sdf.format(regdate);
            //输出借书日期
            Date parse = sdf.parse(s);
            borrowBook.setReaderid(readerid);
            borrowBook.setISBN(ISBN);
            borrowBook.setBorrowdate(parse);
            borrowBookDao.borrowBooks(connection, borrowBook);
            changesInTheNumberOfBooks(ISBN, false);
            Druid.colseResource(connection, null, null);

        } catch (ParseException parseException) {
            parseException.printStackTrace();
        } catch (FileNotFoundException fileNotFoundException) {
            fileNotFoundException.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    //借书
    //①从reader表获取
    public int getReader_typeID(String readerid) {
        ReaderDaoImpl readerDao = ReaderDaoImpl.getReaderDao();
        try {
            Connection connection = Druid.getConnection();
            List<Reader> all = readerDao.getAll(connection);
            for (int i = 0; i < all.size(); i++) {
                if (readerid.equals(all.get(i).getReaderid())) {
                    return all.get(i).getType();
                }
            }
            all.forEach(System.out::println);
            Druid.colseResource(connection, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    //1.1  reader——type获取 1.借书数量，判断是否可以继续接
    public int judgmentBorrowMax(int id) {
        ReaderTypeDaoImpl readerTypeDao = ReaderTypeDaoImpl.getReaderTypeDao();
        try {
            Connection connection = Druid.getConnection();
            List<ReaderType> all = readerTypeDao.getAll(connection);
            for (int i = 0; i < all.size(); i++) {
                if (id == all.get(i).getId()) {
                    return all.get(i).getMaxborrownum();
                }
            }
            Druid.colseResource(connection, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    //1.2  reader——type获取 1.借书天数，判断是否要罚金
    public int judgmentBorrowLitmit(int id) {

        ReaderTypeDaoImpl readerTypeDao = ReaderTypeDaoImpl.getReaderTypeDao();
        try {
            Connection connection = Druid.getConnection();
            List<ReaderType> all = readerTypeDao.getAll(connection);
            for (int i = 0; i < all.size(); i++) {
                if (id == (all.get(i).getId())) {
                    return all.get(i).getReaderlimit();
                }
            }
            Druid.colseResource(connection, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static void changesInTheNumberOfBooks(String ISBN, boolean additionAndSubtraction) throws Exception {
        BookBaseDao2Impl baseDao2 = BookBaseDao2Impl.getBaseDao2();
        Connection connection = null;
        try {
            connection = Druid.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Book bookByISBN = baseDao2.getBookByISBN(Druid.getConnection(), ISBN);
        int number = bookByISBN.getNumber();
        if (additionAndSubtraction) {
            number++;
        } else {
            number--;
            System.out.println(number);
        }
        bookByISBN.setNumber(number);
        try {
            baseDao2.update(Druid.getConnection(), bookByISBN.getISBN(), bookByISBN);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void returnBooks() {
        BorrowBook borrowBook = new BorrowBook();
        Connection connection = null;
        try {
            connection = Druid.getConnection();
            BorrowBookDaoImpl borrowBookDao = new BorrowBookDaoImpl();
            System.out.println("当前借书记录");
            List<BorrowBook> borrowBooks1 = borrowBookDao.getAll(connection);
            ArrayList<BorrowBook> borrowBooks = MyTool.printArrs(borrowBooks1);
            if(borrowBooks.size()==0){
                System.out.println("没有待还的图书：");
                return;
            }
            System.out.println("输入你要归还的借书记录(直接按确定退出)——序号");
            Integer typeIndex = MyTool.getTypeIndex(borrowBooks.size());
            String readerid = borrowBooks.get(typeIndex).getReaderid();
            if(typeIndex==null){
                System.out.println("退出成功");
                return;
            }
            borrowBook.setReaderid(readerid);
            String ISBN = borrowBooks.get(typeIndex).getISBN();
            System.out.println(ISBN);
            List<BorrowBook> all = borrowBookDao.getAll(connection);
            for (int i = 0; i < all.size(); i++) {
                if (ISBN.equals(all.get(i).getISBN())&&readerid.equals(all.get(i).getReaderid())) {
                    if (all.get(i).getReturndate() != null) {
                        System.out.println("该书已经被还，重新选择");
                        return;
                    }
                }
            }
            System.out.println("还书时间自己设定（直接按确定退出）");
            Date regdate = MyTool.getDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String s = sdf.format(regdate);
            if(regdate==null){
                System.out.println("退出成功");
                return;
            }
            Date returnTime = sdf.parse(s);
            Date borrowdate = borrowBooks.get(typeIndex).getBorrowdate();
            int difference = compareDate(returnTime, borrowdate);
            System.out.println("时间差");
            System.out.println(difference);
            if (difference < 0) {
                System.out.println("你还书的时间设置有误重新操作");
                return;
            }
            borrowBook.setISBN(ISBN);
            borrowBook.setReaderid(readerid);
            borrowBook.setReturndate(returnTime);
            borrowBookDao.returnBooks(Druid.getConnection(), borrowBook);
            System.out.println("还书成功");
            changesInTheNumberOfBooks(ISBN, true);
          //  计算时间差
           // borrowBookDao.timeDifference(connection,borrowBook);
           // 计算罚金
            int reader_typeID = getReader_typeID(readerid);
            int limit = judgmentBorrowLitmit(reader_typeID);

            if (limit < difference) {
                System.out.println("逾期了"+(Integer.parseInt(FineServiceImpl.returnFine(readerid)))+"天");
                int i = (difference - limit) * (Integer.parseInt(FineServiceImpl.returnFine(readerid)));
                System.out.println("请缴纳借书费用" + i + "元");
                borrowBook.setFine(i);
                Connection connection1 = Druid.getConnection();
                BorrowBookDaoImpl.returnFine(connection1, borrowBook);
                System.out.println("缴费成功");
                Druid.colseResource(connection1, null, null);
            }
            Druid.colseResource(connection, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int compareDate(Date d1, Date d2) {
        // TODO Auto-generated method stub
        long dif = d1.getTime() - d2.getTime();
        long day = dif / (24 * 60 * 60 * 1000);
        return (int) day;
    }

    //还书
    //首先设置还书日期
    @Override
    public List<BorrowBook> getAll() {

        BorrowBookDaoImpl borrowBook = BorrowBookDaoImpl.getBorrowBook();
        Connection connection = null;
        try {
            connection = Druid.getConnection();

        } catch (Exception e) {
            e.printStackTrace();
        }
        List<BorrowBook> all = borrowBook.getAll(connection);
        if(all.size()==0){
            System.out.println("还没有借阅记录：");
            return null;
        }
        all.forEach(System.out::println);
        Druid.colseResource(connection, null, null);
        return null;
    }

    public static List<BorrowBook> fineLog() {
        BorrowBookDaoImpl borrowBook = BorrowBookDaoImpl.getBorrowBook();
        Connection connection = null;
        try {
            connection = Druid.getConnection();

        } catch (Exception e) {
            e.printStackTrace();
        }
        List<BorrowBook> all = borrowBook.getAll(connection);
        System.out.println("逾期账单信息");
        for (int i = 0; i < all.size(); i++) {
            if (all.get(i).getFine() != 0) {
                System.out.println(all.get(i).toString());
            }
        }
        Druid.colseResource(connection, null, null);
        return null;
    }
    public int getBorrowMax(String readerId) {
        BorrowBookDaoImpl borrowBook = BorrowBookDaoImpl.getBorrowBook();
        Connection connection = null;
        try {
            connection = Druid.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<BorrowBook> all = borrowBook.getAll(connection);
        int number = 0;
        for (int i = 0; i < all.size(); i++) {
            if (readerId.equals(all.get(i).getReaderid())) {
                if(all.get(i).getReturndate()==null){
                    number++;
                }
            }
        }
        Druid.colseResource(connection, null, null);
        return number;
    }

    public static void main(String[] args) {
           }
}
